<template>
  <div class="markdown-renderer">
    <!-- 编辑模式 -->
    <div v-if="editable && isEditing" class="markdown-editor">
      <div class="editor-header">
        <span class="editor-title">{{ label || '编辑内容' }}</span>
        <div class="editor-actions">
          <el-button size="mini" @click="togglePreview">
            {{ showPreview ? '隐藏预览' : '显示预览' }}
          </el-button>
          <el-button size="mini" type="primary" @click="saveContent">保存</el-button>
          <el-button size="mini" @click="cancelEdit">取消</el-button>
        </div>
      </div>
      
      <div class="editor-content" :class="{ 'split-view': showPreview }">
        <!-- 编辑区域 -->
        <div class="editor-input" :class="{ 'half-width': showPreview }">
          <el-input
            type="textarea"
            v-model="editContent"
            :placeholder="placeholder || '支持Markdown语法，如：**粗体** *斜体* `代码` 等'"
            :rows="rows"
            class="markdown-textarea"
          />
          <div class="markdown-tips">
            <small>
              支持：**粗体** *斜体* `代码` [链接](url) - 列表 1. 有序列表 > 引用 ```代码块```
            </small>
          </div>
        </div>
        
        <!-- 预览区域 -->
        <div v-if="showPreview" class="editor-preview half-width">
          <div class="preview-header">预览</div>
          <div class="markdown-content" v-html="renderedContent"></div>
        </div>
      </div>
    </div>
    
    <!-- 显示模式 -->
    <div v-else class="markdown-display">
      <div v-if="editable && showLabel" class="display-header">
        <span class="display-label">{{ label }}</span>
        <el-button size="mini" type="text" @click="startEdit" class="edit-btn">
          <i class="el-icon-edit"></i> 编辑
        </el-button>
      </div>

      <!-- 编辑按钮（无标签模式） -->
      <div v-if="editable && !showLabel" class="edit-only-header">
        <el-button size="mini" type="text" @click="startEdit" class="edit-btn-compact">
          <i class="el-icon-edit"></i>
        </el-button>
      </div>
      
      <div class="content-wrapper">
        <div
          class="markdown-content"
          :class="{
            'collapsed': collapsible && !isExpanded && needsExpansion,
            'expandable': collapsible && needsExpansion
          }"
          :style="collapsible && !isExpanded && needsExpansion ? { maxHeight: maxHeight + 'px' } : {}"
          v-html="renderedContent">
        </div>
        <!-- 渐变遮罩 -->
        <div
          v-if="collapsible && !isExpanded && needsExpansion"
          class="fade-mask">
        </div>
      </div>

      <!-- 展开/收起按钮 -->
      <div
        v-if="collapsible && needsExpansion"
        class="expand-toggle"
        @click="toggleExpansion">
        <span class="toggle-text">
          {{ isExpanded ? '收起' : '展开全部' }}
        </span>
        <i :class="isExpanded ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i>
      </div>

      <div v-if="!value && editable" class="empty-placeholder" @click="startEdit">
        <i class="el-icon-edit"></i>
        {{ placeholder || '点击添加内容（支持Markdown）' }}
      </div>
    </div>
  </div>
</template>

<script>
import { marked } from 'marked'

export default {
  name: 'MarkdownRenderer',
  props: {
    value: {
      type: String,
      default: ''
    },
    editable: {
      type: Boolean,
      default: false
    },
    label: {
      type: String,
      default: ''
    },
    placeholder: {
      type: String,
      default: ''
    },
    rows: {
      type: Number,
      default: 6
    },
    maxHeight: {
      type: Number,
      default: 80  // 默认最大高度80px (约3行文本)
    },
    collapsible: {
      type: Boolean,
      default: true  // 默认支持折叠
    },
    showLabel: {
      type: Boolean,
      default: false  // 默认不显示标签，避免重复
    }
  },
  
  data() {
    return {
      isEditing: false,
      editContent: '',
      showPreview: false,
      isExpanded: false,
      needsExpansion: false
    }
  },
  
  computed: {
    renderedContent() {
      if (!this.value && !this.editContent) return '';
      
      const content = this.isEditing ? this.editContent : this.value;
      
      // 配置marked选项
      marked.setOptions({
        breaks: true,        // 支持换行
        gfm: true,          // 支持GitHub风格Markdown
        sanitize: false,    // 允许HTML（在生产环境中可能需要调整）
        smartLists: true,   // 智能列表
        smartypants: true   // 智能标点
      });
      
      return marked(content || '');
    }
  },
  
  mounted() {
    this.checkContentHeight();
  },

  watch: {
    value() {
      this.$nextTick(() => {
        this.checkContentHeight();
      });
    }
  },

  methods: {
    startEdit() {
      this.editContent = this.value || '';
      this.isEditing = true;
      this.showPreview = false;
    },

    toggleExpansion() {
      this.isExpanded = !this.isExpanded;
    },

    checkContentHeight() {
      if (!this.collapsible || !this.value) {
        this.needsExpansion = false;
        return;
      }

      this.$nextTick(() => {
        const contentEl = this.$el.querySelector('.markdown-content');
        if (contentEl) {
          const actualHeight = contentEl.scrollHeight;
          this.needsExpansion = actualHeight > this.maxHeight;
        }
      });
    },
    
    cancelEdit() {
      this.isEditing = false;
      this.editContent = '';
      this.showPreview = false;
    },
    
    saveContent() {
      this.$emit('input', this.editContent);
      this.$emit('change', this.editContent);
      this.isEditing = false;
      this.showPreview = false;
      this.$message.success('内容已保存');
    },
    
    togglePreview() {
      this.showPreview = !this.showPreview;
    }
  }
}
</script>

<style scoped>
.markdown-renderer {
  width: 100%;
}

/* 编辑模式样式 */
.markdown-editor {
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  overflow: hidden;
}

.editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #f5f7fa;
  border-bottom: 1px solid #dcdfe6;
}

.editor-title {
  font-weight: 500;
  color: #303133;
}

.editor-content {
  display: flex;
  min-height: 200px;
}

.split-view {
  height: 400px;
}

.editor-input, .editor-preview {
  flex: 1;
}

.half-width {
  width: 50%;
}

.editor-input {
  display: flex;
  flex-direction: column;
}

.markdown-textarea {
  flex: 1;
  border: none;
}

.markdown-textarea >>> .el-textarea__inner {
  border: none;
  border-radius: 0;
  resize: none;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 14px;
  line-height: 1.6;
}

.markdown-tips {
  padding: 8px 12px;
  background: #fafafa;
  border-top: 1px solid #eee;
  color: #909399;
  font-size: 12px;
}

.editor-preview {
  border-left: 1px solid #dcdfe6;
  background: #fafafa;
}

.preview-header {
  padding: 12px 16px;
  background: #f0f2f5;
  border-bottom: 1px solid #dcdfe6;
  font-weight: 500;
  color: #606266;
}

/* 显示模式样式 */
.display-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.display-label {
  font-weight: 500;
  color: #303133;
}

.edit-btn {
  padding: 4px 8px;
  color: #409eff;
}

.edit-btn:hover {
  background: #ecf5ff;
}

.edit-only-header {
  position: absolute;
  top: 4px;
  right: 4px;
  z-index: 10;
}

.edit-btn-compact {
  padding: 2px 6px !important;
  font-size: 12px;
  color: #909399;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 4px;
  opacity: 0;
  transition: opacity 0.2s ease;
}

.markdown-display:hover .edit-btn-compact {
  opacity: 1;
}

/* Markdown内容样式 */
.markdown-content {
  padding: 12px;
  line-height: 1.5;
  color: #303133;
  background: white;
  border-radius: 4px;
  min-height: 40px;
}

.markdown-content >>> h1,
.markdown-content >>> h2,
.markdown-content >>> h3,
.markdown-content >>> h4,
.markdown-content >>> h5,
.markdown-content >>> h6 {
  margin: 16px 0 8px 0;
  font-weight: 600;
  color: #303133;
}

.markdown-content >>> h1 { font-size: 24px; }
.markdown-content >>> h2 { font-size: 20px; }
.markdown-content >>> h3 { font-size: 18px; }
.markdown-content >>> h4 { font-size: 16px; }

.markdown-content >>> p {
  margin: 8px 0;
}

.markdown-content >>> ul,
.markdown-content >>> ol {
  margin: 8px 0;
  padding-left: 24px;
}

.markdown-content >>> li {
  margin: 4px 0;
}

.markdown-content >>> blockquote {
  margin: 16px 0;
  padding: 8px 16px;
  background: #f5f7fa;
  border-left: 4px solid #409eff;
  color: #606266;
}

.markdown-content >>> code {
  padding: 2px 6px;
  background: #f5f7fa;
  border-radius: 3px;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 13px;
  color: #e6a23c;
}

.markdown-content >>> pre {
  margin: 16px 0;
  padding: 16px;
  background: #f5f7fa;
  border-radius: 6px;
  overflow-x: auto;
}

.markdown-content >>> pre code {
  padding: 0;
  background: none;
  color: #303133;
}

.markdown-content >>> strong {
  font-weight: 600;
  color: #303133;
}

.markdown-content >>> em {
  font-style: italic;
  color: #606266;
}

.markdown-content >>> a {
  color: #409eff;
  text-decoration: none;
}

.markdown-content >>> a:hover {
  text-decoration: underline;
}

/* 空状态样式 */
.empty-placeholder {
  padding: 32px;
  text-align: center;
  color: #c0c4cc;
  background: #fafafa;
  border: 2px dashed #dcdfe6;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.empty-placeholder:hover {
  border-color: #409eff;
  color: #409eff;
  background: #ecf5ff;
}

.empty-placeholder i {
  margin-right: 8px;
  font-size: 16px;
}

/* 折叠展开功能样式 */
.content-wrapper {
  position: relative;
}

.markdown-content.collapsed {
  overflow: hidden;
}

.fade-mask {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 30px;
  background: linear-gradient(transparent, rgba(255, 255, 255, 0.9));
  pointer-events: none;
}

.expand-toggle {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
  padding: 6px 10px;
  margin-top: 6px;
  background: #f8f9fa;
  border: 1px solid #e8eaec;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 12px;
  color: #606266;
}

.expand-toggle:hover {
  background: #ecf5ff;
  border-color: #409eff;
  color: #409eff;
}

.toggle-text {
  font-weight: 500;
}

.expand-toggle i {
  font-size: 12px;
  transition: transform 0.2s ease;
}
</style>
